﻿using DocumentFormat.OpenXml.Drawing.Spreadsheet;
using DocumentFormat.OpenXml.Packaging;
using System;
using System.IO;
using System.Linq;

namespace expFun
{
    public class ExpPic
    {
        public static void ExtractImages(string excelFilePath, string outputDirectory = "")
        {
            if (string.IsNullOrWhiteSpace(outputDirectory) || !Directory.Exists(outputDirectory))
            {
                outputDirectory = Path.GetDirectoryName(excelFilePath) ?? AppDomain.CurrentDomain.BaseDirectory;
            }
            // 获取 Excel 文件名（不带扩展名）
            string fileName = Path.GetFileNameWithoutExtension(excelFilePath);

            // 创建以文件名为目录的输出路径
            string mainOutputDirectory = Path.Combine( outputDirectory, fileName);

            // 如果主输出目录已存在，则删除
            if (Directory.Exists(mainOutputDirectory))
            {
                Directory.Delete(mainOutputDirectory, true); // true 表示递归删除
            }

            // 确保主输出目录存在
            Directory.CreateDirectory(mainOutputDirectory);

            // 创建日志文件路径
            string logFilePath = Path.Combine(mainOutputDirectory, "log.txt");

            // 使用 StreamWriter 来写入日志文件
            using (StreamWriter logWriter = new StreamWriter(logFilePath, append: true))
            {
                try
                {
                    // 打开 Excel 文件
                    using (SpreadsheetDocument spreadsheetDocument = SpreadsheetDocument.Open(excelFilePath, false))
                    {
                        var workbookPart = spreadsheetDocument?.WorkbookPart;
                        if (workbookPart == null)
                        {
                            string error = "无法获取 WorkbookPart。";
                            Console.WriteLine(error);
                            logWriter.WriteLine($"{DateTime.Now}: {error}");
                            return;
                        }

                        // 遍历所有的工作表
                        foreach (var worksheetPart in workbookPart.WorksheetParts)
                        {
                            var worksheetName = workbookPart.Workbook.Descendants<DocumentFormat.OpenXml.Spreadsheet.Sheet>()
                                .FirstOrDefault(s => s?.Id?.Value == workbookPart.GetIdOfPart(worksheetPart))?.Name ;

                            if (worksheetName == null)
                            {
                                string error = "无法获取工作表名称。";
                                Console.WriteLine(error);
                                logWriter.WriteLine($"{DateTime.Now}: {error}");
                                continue;
                            }

                            // 为当前工作表创建子文件夹
                            string worksheetOutputDirectory = Path.Combine(mainOutputDirectory, worksheetName );
                            if (!Directory.Exists(worksheetOutputDirectory))
                            {
                                Directory.CreateDirectory(worksheetOutputDirectory);
                            }

                            var drawingsPart = worksheetPart?.DrawingsPart;
                            if (drawingsPart == null)
                            {
                                string warning = $"工作表 {worksheetName} 没有绘图部分。";
                                Console.WriteLine(warning);
                                logWriter.WriteLine($"{DateTime.Now}: {warning}");
                                continue;
                            }

                            // 遍历所有 TwoCellAnchor
                            foreach (var anchor in drawingsPart.WorksheetDrawing.Descendants<TwoCellAnchor>())
                            {
                                var picture = anchor.Descendants<DocumentFormat.OpenXml.Drawing.Spreadsheet.Picture>().FirstOrDefault();
                                if (picture == null) continue;

                                var blipFill = picture.GetFirstChild<DocumentFormat.OpenXml.Drawing.Spreadsheet.BlipFill>();
                                var relationshipId = blipFill?.Blip?.Embed?.Value;
                                if (relationshipId == null) continue;

                                var imagePart = drawingsPart.GetPartById(relationshipId) as ImagePart;
                                if (imagePart == null)
                                {
                                    string error = "未找到图像部分。";
                                    Console.WriteLine(error);
                                    logWriter.WriteLine($"{DateTime.Now}: {error}");
                                    continue;
                                }

                                // 获取图片的起始和结束单元格坐标
                                int startColumn = int.Parse(anchor.FromMarker?.ColumnId?.Text ?? "-1") + 1; // 列加 1
                                int startRow = int.Parse(anchor.FromMarker?.RowId?.Text ?? "-1") + 1; // 行加 1
                                int endColumn = int.Parse(anchor.ToMarker?.ColumnId?.Text ?? "-1") + 1; // 列加 1
                                int endRow = int.Parse(anchor.ToMarker?.RowId?.Text ?? "-1") + 1; // 行加 1

                                string coordinates = $"(R{startRow}C{startColumn}-R{endRow}C{endColumn})";
                                string? picName = picture?.NonVisualPictureProperties?.NonVisualDrawingProperties?.Name ?? "NULL";
                                // 获取图片文件名，包含坐标信息
                                string imageFileName = $"Image_{coordinates}_{picName}.png";
                                string outputPath = Path.Combine(worksheetOutputDirectory, imageFileName);

                                // 保存图片
                                using (var stream = imagePart.GetStream())
                                {
                                    using (var fileStream = new FileStream(outputPath, FileMode.Create, FileAccess.Write))
                                    {
                                        stream.CopyTo(fileStream);
                                    }
                                }

                                // 记录日志，包含图片坐标信息
                                string successMessage = $"图片已保存至: {outputPath}, 坐标: {coordinates}";
                                Console.WriteLine(successMessage);
                                logWriter.WriteLine($"{DateTime.Now}: {successMessage}");
                            }
                        }
                    }
                }
                catch (Exception ex)
                {
                    string errorMessage = $"导出图片时发生错误: {ex.Message}";
                    Console.WriteLine(errorMessage);
                    logWriter.WriteLine($"{DateTime.Now}: {errorMessage}");
                }
            }
        }
    }
}
